package com.sjt.ThreadDemo;

import javafx.concurrent.Worker;
import lombok.extern.slf4j.Slf4j;

import java.util.HashSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
@Slf4j
public class ThreadPool {

   private BlockingQueue<Runnable>taskQueue;

   private HashSet<Worker>workers=new HashSet<>();

   private int poolCapacity;

   public ThreadPool(int poolCapacity,int count ) {
      this.poolCapacity = poolCapacity;
      this.taskQueue=new LinkedBlockingQueue<>(count);
   }

   public void execute(Runnable task)   {
      synchronized (workers)
      {
         if(workers.size()<poolCapacity){
            Worker worker=new Worker(task);
            workers.add(worker);
            worker.start();
         }else{
               if(taskQueue.size()<poolCapacity)
               {
                  taskQueue.add(task);
               }
         }

      }
   }
   class Worker extends Thread{
      private Runnable task;
      public Worker(Runnable task){
         this.task=task;
      }
      @Override
      public void run() {

         while(task!=null||(task=taskQueue.poll())!=null)
         {
            log.debug(Thread.currentThread().getName()+"取出 执行完毕");
            task.run();
            log.debug(Thread.currentThread().getName()+"存入 执行完毕");
            task=null;
         }

      }
   }
}

